package 链表中的节点每k个一组反转;

import util.ListNode;

import java.util.List;

public class reverseKGroup {
    public static void main(String[] args) {

    }

    public ListNode reverseBetween(ListNode head, int k){
        if(head == null || k <= 1 || head.next == null){
            return head;
        }

        ListNode dummy = new ListNode(-1);
        dummy.next = head;

        ListNode pre = dummy;
        ListNode end = dummy;

        while (end.next != null){
            for (int i = 0; i < k && end != null; i++) {
                end = end.next;
            }

            if (end.next == null){
                break;
            }

            ListNode next = end.next;
            //断开
            end.next = null;
            ListNode start = pre.next;
            //断开
            pre.next = null;

            //连接反转后的头节点
            pre.next = reverseList(start);

            //连接反转后的尾结点
            start.next = next;

            //到达下一个待反转组的前一个节点
            pre = start;
            end = start;

        }
        return dummy.next;
    }

    public ListNode reverseList(ListNode head){
        if (head == null || head.next ==null){
            return head;
        }

        ListNode cur = reverseList(head.next);

        head.next.next = head;
        head.next = null;
        return cur;
    }
}
